from pynput import mouse
from lib.cache import file_cache

import threading
import time


class MouseCls(threading.Thread):

    def __init__(self):
        print("mouse 初始化")
        super().__init__()

        self.mouse_listen = mouse.Listener()
        self.__mouse_running_flag = True

    def mouse_check(self):
        if not self.__mouse_running_flag:
            return False

    @file_cache(filename='testdata')
    def on_move(self, x, y):
        print(f'{time.ctime()}pointer moved to {(x,y)}')
        return self.mouse_check()

    @file_cache(filename='testdata')
    def on_click(self, x, y, button, pressed):
        print(f"鼠标在坐标{str((x, y))}处，{'按下' if pressed else '松开'}{button}")
        return self.mouse_check()

    @file_cache(filename='testdata')
    def on_scroll(self, x, y, dx, dy):
        print('Scrolled {0}'.format((x, y)))
        print(dx, dy)
        return self.mouse_check()

    def run(self) -> None:
        with mouse.Listener(on_move=self.on_move,
                            on_click=self.on_click,
                            on_scroll=self.on_scroll) as listener:
            self.mouse_listen = listener
            self.mouse_listen.join()

    def mouse_start(self):
        print("鼠标监听开始。。。。。。")
        self.__mouse_running_flag = True
        self.mouse_listen = mouse.Listener(on_move=self.on_move,
                                           on_click=self.on_click,
                                           on_scroll=self.on_scroll)
        self.mouse_listen.start()
        self.mouse_listen.join()

    def mouse_stop(self):
        self.__mouse_running_flag = False
        mouse.Controller().move(0, 0)


if __name__ == '__main__':
    mc = MouseCls()
    print('1.Start runing...')
    mc.start()
    time.sleep(20)
    mc.mouse_stop()

